import { app } from 'electron'
import fs, { promises as fsPromises } from 'fs'
import path from 'path'
import { v4 as uuidV4 } from 'uuid'

// 临时文件夹名称
const _TEMP_FOLDER_NAME = '.temp'
// 用户数据文件夹路径
const _USER_DATA_PATH = app.getPath('userData')

// 保存文件
export async function saveFile(folderPath, fileName, buffer) {
  const filePath = path.join(folderPath, fileName)
  try {
    if (!fs.existsSync(folderPath)) {
      await fs.mkdirSync(folderPath, { recursive: true })
    }
    await fsPromises.writeFile(filePath, buffer)
  } catch (error) {
    console.log(error)
    return ''
  }
  return filePath
}

// 删除文件
export async function deleteFile(filePath) {
  try {
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath)
    }
  } catch (error) {
    console.log(error)
  }
}
// 删除文件夹
export async function deleteFolder(folderPath) {
  try {
    if (fs.existsSync(folderPath)) {
      // fs.rmdir(folderPath)
      fs.rmSync(folderPath, { recursive: true, force: true })
    }
  } catch (error) {
    console.log(error)
  }
}

// 创建临时文件夹
export async function saveTempFile(fileName, buffer) {
  const folderPath = path.join(_USER_DATA_PATH, _TEMP_FOLDER_NAME)
  fileName = uuidV4() + '-' + fileName
  const filePath = await saveFile(folderPath, fileName, buffer)
  return filePath
}

// 删除临时文件夹
export async function deleteTempFolder() {
  const folderPath = path.join(_USER_DATA_PATH, _TEMP_FOLDER_NAME)
  await deleteFolder(folderPath)
}

// 保存配置
export function setConfig(config, type = 'app') {
  const filePath = path.join(_USER_DATA_PATH, type + '-config.json')
  if (typeof config === 'object') {
    config = JSON.stringify(config)
  }
  return fsPromises.writeFile(filePath, config)
}

// 获取配置
export async function getConfig(type = 'app') {
  const filePath = path.join(_USER_DATA_PATH, type + '-config.json')
  try {
    const config = await fsPromises.readFile(filePath, 'utf-8')
    return JSON.parse(config)
  } catch (error) {
    return {}
  }
}
